﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace SysSU.JSONRPC
{
    public class JSONRPC2Error : Exception
    {
        public static readonly JSONRPC2Error PARSE_ERROR = new JSONRPC2Error(-32700, "JSON parse error");
        public static readonly JSONRPC2Error INVALID_REQUEST = new JSONRPC2Error(-32600, "Invalid request");
        public static readonly JSONRPC2Error METHOD_NOT_FOUND = new JSONRPC2Error(-32601, "Method not found");
        public static readonly JSONRPC2Error INVALID_PARAMS = new JSONRPC2Error(-32602, "Invalid parameters");
        public static readonly JSONRPC2Error INTERNAL_ERROR = new JSONRPC2Error(-32603, "Internal error");

        public int Code { get; private set; }

        public Object Content { get; set; }

        public JSONRPC2Error(int code, string message) 
            : base(message)
        {
            Code = code;
        }

        public JSONRPC2Error(int code, string message, Object content)
            : base(message)
        {
            Code = code;
            Content = content;
        }

        public JObject ToJSON()
        {
            JObject json = new JObject();

		    json["code"] = Code;
		    json["message"] = base.Message;
            if (Content != null)
            {
                json["data"] = JObject.Parse(JsonConvert.SerializeObject(Content));
		    }

            return json;
        }

        public override string ToString()
        {
            return ToJSON().ToString();
        }
    }
}
